package com.wish.bio;

import com.wish.common.MyUtils;

import java.io.*;
import java.net.Socket;

/**
 * @author tantexian
 * @since 2016/6/24
 */
public class SmartClient {

    public static void main(String[] args) {
        final int port = args.length >= 1 ? Integer.parseInt(args[0]) : MyUtils.getDefaultPort();

        Socket socket = null;
        BufferedReader bufferedReaderScoket = null;
        BufferedReader bufferedReaderSystemIn = null;
        PrintWriter printWriter = null;

        try {
            socket = new Socket(MyUtils.getDefaultServerAddr(), port);

            bufferedReaderScoket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));

            printWriter.println("what's you name");
            printWriter.flush();
            String robotResp = bufferedReaderScoket.readLine();
            System.out.println("The answer from robot is: " + robotResp + "\nPlease input you question ...");

            while (true){
                bufferedReaderSystemIn = new BufferedReader(new InputStreamReader(System.in));
                String input = bufferedReaderSystemIn.readLine();
                if (input==null || input.length() == 0) {
                    continue;
                }
                if(input.contains("exit") || input.contains("bye")){
                    break;
                }
                printWriter.println(input);
                printWriter.flush();
                robotResp = bufferedReaderScoket.readLine();
                System.out.println(robotResp);
            }



        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReaderScoket != null) {
                    bufferedReaderScoket.close();
                }
                if (bufferedReaderSystemIn != null) {
                    bufferedReaderSystemIn.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}
